import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import ActivityListABI from '../contract/ABIs/ActivityList.json'; // 活动列表合约 ABI
import MaterialListABI from '../contract/ABIs/MaterialList.json'; // 材料列表合约 ABI
import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI 
import UserABI from '../contract/ABIs/User.json'; // 用户合约 ABI
import { Table, Modal } from 'antd';
import ActivityListAddress from '../contract/ADDRESSes/ActivityListAddress.js'; // 活动列表合约地址
import MaterialListAddress from '../contract/ADDRESSes/MaterialListAddress.js'; // 材料列表合约地址
import UserListAddress from '../contract/ADDRESSes/UserListAddress'; // 用户列表合约地址
import UserNavBar from './nav/UserNavBar.js';
import gb from '../static/bootstrap/images/gb.svg';
import us from '../static/bootstrap/images/us.svg';
import user3 from '../static/bootstrap/images/user3.png';
import Head from './nav/Head.js';

function formatDate(timestamp) {
  if (timestamp) {
    const date = new Date(Number(timestamp) * 1000); // 将BigInt转换为Number后再进行计算
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
  }
  return '';
}
const DoActivity = () => {
  const [web3, setWeb3] = useState(null);
  // 使用 useParams 获取路由参数中的地址信息
  const { address } = useParams();
  const [contractActivityList, setcontractActivityList] = useState(null);
  const [contractMaterialList, setcontractMaterialList] = useState(null);
  const [contractUserList, setContractUserList] = useState(null);
  const [contractUser, setcontractUser] = useState(null);
  const [isUser, setisUser] = useState(false);
  const [activityList, setactivityList] = useState('') //查看所有活动列表
  const [activityId, setactivityId] = useState('');
  const [IsList, setIsList] = useState(false);//控制是否显示列表
  const [categoryFilter, setCategoryFilter] = useState('');//用于通过分类查询
  const [updateModalOpen, setUpdateModalOpen] = useState(false);
  const [joinedRules, setJoinedRules] = useState([]);//参加成功标识

  const columns = [
    {
      title: '活动ID',
      dataIndex: 'Id',
      key: 'Id',
      render: (text) => {
        const newText = text.toString(); // 将文本转换为字符串
        return <span style={{ color: 'black' }}>{newText}</span>;
      },
    },
    {
      title: '活动名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => (
        <span style={{ color: 'black' }}>
          {text}
        </span>
      )
    },
    {
      title: '活动种类',
      dataIndex: 'category',
      key: 'category',
      render: (text) => (
        <span style={{ color: 'black' }}>
          {text}
        </span>
      )
    },
    {
      title: '管理员地址',
      dataIndex: 'admin',
      key: 'admin',
      render: (text) => {
        const newText = text.toString(); // 将文本转换为字符串
        return <span style={{ color: 'black' }}>{newText}</span>;
      },
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (text) => (
        <span style={{ color: 'black' }}>{formatDate(text)}</span>
      ),
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      render: (text) => (
        <span style={{ color: 'black' }}>{formatDate(text)}</span>
      ),
    },
    {
      title: '活动描述',
      dataIndex: 'description',
      key: 'description',
      render: (text) => (
        <span style={{ color: 'black' }}>
          {text}
        </span>
      )
    },
    {
      title: '是否有效',
      dataIndex: 'isValid',
      key: 'isValid',
      render: (text) => (
        <span style={{ color: 'black' }}>{text == true ? '有效' : '无效'}</span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (text, rule) => (
        <button className="btn btn-primary btn-lg d-block w-100" type="primary" onClick={() => JoinActivity(rule)}>
          {joinedRules.includes(rule) ? '已参加' : '参加'}
        </button>
      ),
    }
  ];

  useEffect(() => {
    async function init() {
      // 连接到以太坊网络
      if (window.ethereum) {
        const web3Instance = new Web3(window.ethereum);
        try {
          // 请求用户授权
          await window.ethereum.enable();
          setWeb3(web3Instance);

          // 创建活动列表合约实例
          const activityListInstance = new web3Instance.eth.Contract(
            ActivityListABI,
            ActivityListAddress
          );
          setcontractActivityList(activityListInstance);

          // 创建材料列表合约实例
          const materialListInstance = new web3Instance.eth.Contract(
            MaterialListABI,
            MaterialListAddress
          );
          setcontractMaterialList(materialListInstance);

          // 创建用户列表合约实例
          const userListInstance = new web3Instance.eth.Contract(
            UserListABI,
            UserListAddress
          );
          setContractUserList(userListInstance);

          // 创建用户合约实例
          const userInstance = new web3Instance.eth.Contract(
            UserABI,
            address
          );
          setcontractUser(userInstance);

          // 获取当前用户的以太坊账户地址
          const accounts = await web3Instance.eth.getAccounts();
          const currentAddress = accounts[0];
          // 获取用户合约的 owner 地址
          const ownerAddress = await userInstance.methods.getUserAddr().call();
          // 检查当前账户是否是用户本人
          setisUser(currentAddress === ownerAddress);

          // 自动获取学生信息列表
          await GetAllActivity(web3Instance, activityListInstance);
        } catch (error) {
          console.error(error);
        }
      } else {
        console.error('请安装以太坊浏览器插件，如 MetaMask');
      }
    }
    init();
  }, [address]);

  // 用户参加活动函数
  const JoinActivity = async (rule) => {
    setUpdateModalOpen(false);
    if (contractActivityList && contractUser) {
      try {
        const accounts = await web3.eth.getAccounts();
        const fromAddress = accounts[0];

        // 检查用户是否已经参加了这个活动    
        const hasParticipated = await contractUser.methods.judgeStateActivity(rule.Id).call();
        console.log("hasParticipated:", hasParticipated);
        if (hasParticipated) {
          alert("您已经参加了这个活动！");
          return;
        }
        // 调用智能合约的joinActivity方法  
        await contractActivityList.methods.joinActivity(address, fromAddress, rule.Id).send({ from: fromAddress });
        setJoinedRules([true, rule]);
        alert("参加成功");
      } catch (error) {
        console.error(error);
        alert("参加失败");
      }
    }
  };

  // 获取所有活动
  const GetAllActivity = async (web3Instance, activityListInstance) => {
    if (activityListInstance) {
      try {
        const accounts = await web3Instance.eth.getAccounts();
        const fromAddress = accounts[0];
        console.log("fromAddress:", fromAddress);
        // 调用合约函数
        const result = await activityListInstance.methods.getAllActivity().call({ from: fromAddress });
        console.log("返回的活动信息：", result);
        setactivityList(result);
        setIsList(true);//让列表显示出来
      } catch (error) {
        console.error(error);
      }
    };
  };

  //搜索
  const handleFilterActivity = async () => {
    if (contractActivityList) {
      try {
        const filteredActivityList = activityList.filter((activity) => activity.category === categoryFilter);//设置通过类别查询
        setactivityList(filteredActivityList);

        setIsList(true);
      } catch (error) {
        console.error(error);
      }
    }
  };


  return (
    <div>
      {!isUser && (<div>您没有权限访问此页面。</div>)}

      {isUser && (
        <div className="page-wrapper" style={{
          backgroundColor: '#FFFFFF'
        }}>
          <div className="main-container">
            <UserNavBar address={address} />

            <div className="app-container">
              <Head></Head>
              <div className="app-body">
                <div className="container-fluid">

                  <div>
                    <main className="page hire-me-page">
                      <section className="portfolio-block hire-me">
                        <div className="foreground-component">
                          <div className="container">
                            <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                              data-bs-theme="light"
                              style={{
                                backgroundColor: 'rgba(36, 36, 41, 0.6)'
                              }}
                            >
                              <div className="mb-3">
                                <h2>参加活动</h2>
                                {/* <h2>活动列表信息</h2> */}
                                {/* <div style={{ display: 'flex', justifyContent: 'center' }}>
                            <button onClick={GetAllActivity} style={{ marginLeft: '-200px' }}>查询活动列表信息</button>
                        </div> */}
                                <div className="d-flex justify-content-end mt-3">
                                  <div className="input-group mb-3" style={{ maxWidth: '300px' }}>
                                    <input
                                      type="text"
                                      className="form-control"
                                      placeholder="输入活动种类查询"
                                      aria-label="活动种类查询"
                                      aria-describedby="basic-addon2"
                                      value={categoryFilter}
                                      onChange={(e) => setCategoryFilter(e.target.value)}
                                    />
                                    <div className="input-group-append">
                                      <button className="btn btn-primary btn-lg d-block w-100" type="button" onClick={handleFilterActivity}>查询</button>
                                    </div>
                                  </div>
                                </div>
                                {IsList ? (
                                  <Table
                                    dataSource={activityList}
                                    columns={columns} // 确保你已经定义了columns
                                    pagination={{
                                      pageSize: 2,
                                      showTotal: false, // 隐藏总页数
                                      showSizeChanger: false, // 隐藏页面大小选择器
                                      itemRender: (current, type, originalElement) => (
                                        <span style={{ color: 'black' }}>
                                          {current}
                                        </span>
                                      ),
                                    }}
                                  />
                                ) : (
                                  <div>No activity information available.</div>
                                )}
                              </div>
                            </div>
                          </div>
                        </div>
                      </section>
                    </main>
                  </div>


                </div>
              </div>
              <div className="app-footer">
                <span>
                  © Bootstrap Gallery 2023
                </span>
              </div>
            </div>
          </div>

        </div>
      )}
    </div>
  )


};
export default DoActivity;